/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package filetransfer;

import bmechat.client.Client;
import java.net.*;
import java.io.*;

/**
 *
 * @author Owner
 */
public class FileClient implements Runnable {

    String args[];
    Client client;

    public FileClient(String[] args, Client client) {
        this.args = args;
        this.client=client;
    }

    public void run() {
        InputStream is = null;
        try {
            int filesize = Integer.parseInt(args[1]);
            int bytesRead;
            
            Socket sock = new Socket(args[2], 16689);
            PrintWriter out = new PrintWriter(sock.getOutputStream(), true);
            // receive file
            byte[] mybytearray = new byte[filesize];
            is = sock.getInputStream();
            if (args[0] != null) {
                FileOutputStream fos = new FileOutputStream(args[0]);
                BufferedOutputStream bos = new BufferedOutputStream(fos);
                bytesRead = is.read(mybytearray, 0, mybytearray.length);
                
                bos.write(mybytearray, 0, bytesRead);
                bos.flush();
                client.addToChatLog("File received.");
                bos.close();
            }
            sock.close();
        } catch (IOException ex) {
            client.addToChatLog("File transfer failed.");
        }
    }
}
